package com.starbaba.weixin.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.base.common.exception.AppException;
import com.starbaba.weixin.dao.WeixinQRDao;
import com.starbaba.weixin.model.CustomerChannel;
import com.starbaba.weixin.model.QueryListVO;
import com.starbaba.weixin.model.WeixinQRActivityVO;
import com.starbaba.weixin.model.WeixinQRCustomerVO;
import com.starbaba.weixin.model.WeixinQRRecordVO;
import com.starbaba.weixin.model.WeixinRedpackRecord;
import com.starbaba.weixin.model.WeixinRedpackStat;
import com.starbaba.weixin.service.WeixinActivityService;

/**
 * @author Yukinomiu
 * @version 1.0
 */
//@Service("WeixinActivityServiceImpl")
public class WeixinActivityServiceImpl implements WeixinActivityService {

    private static final String CHANNEL_SPLIT_TOKEN = ",";

    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @SuppressWarnings("SpringJavaAutowiringInspection")
    @Autowired
    private WeixinQRDao weixinQRDao;

    @Override
    public QueryListVO getList(Map<String, Object> queryParams) {
        Integer count = weixinQRDao.getCount(queryParams);
        List<WeixinQRActivityVO> data = null;
        if (count != 0) {
            data = weixinQRDao.getList(queryParams);
        }
        return new QueryListVO(count, data);
    }

    @Override
    public QueryListVO getRecordList(Map<String, Object> queryParams) {
        Integer count = weixinQRDao.getRecordCount(queryParams);
        List<WeixinQRRecordVO> data = null;
        if (count != 0) {
            data = weixinQRDao.getRecordList(queryParams);
        }
        return new QueryListVO(count, data);
    }

    @Override
    public QueryListVO getCustomerList(Map<String, Object> queryParams) {
        Set<String> channels = new LinkedHashSet<>();

        String userId = (String) queryParams.get("userId");
        List<CustomerChannel> customerChannels = weixinQRDao.getCustomerChannels(userId);
        for (CustomerChannel customerChannel : customerChannels) {
            String v = customerChannel.getChannels();
            if (v.contains(CHANNEL_SPLIT_TOKEN)) {
                String[] array = v.split(CHANNEL_SPLIT_TOKEN);
                for (String c : array) {
                    c = c.trim();
                    if (c.length() != 0) {
                        channels.add(c);
                    }
                }
            }
            else {
                channels.add(v);
            }
        }

        // 如果当前用户不属于任何渠道, 则显示全部渠道数据
        if (channels.size() != 0) {
            queryParams.put("channels", channels);
        }

        Integer count = weixinQRDao.getCustomerCount(queryParams);
        List<WeixinQRCustomerVO> data = null;
        if (count != 0) {
            data = weixinQRDao.getCustomerList(queryParams);
        }
        return new QueryListVO(count, data);
    }

    @Override
    @Transactional
    public void changeChannelName(Map<String, Object> params) {
        weixinQRDao.changeCouponCodeChannel(params);
        weixinQRDao.changeRecordChannel(params); // 如果能保证某个优惠码只能在未被用户领取的情况下修改渠道名称, 则可以去除此逻辑以提高性能
    }

    @Override
    public Set<String> getAllChannels() {
        Set<String> set = weixinQRDao.getAllChannels();
        if (set == null) {
            set = new HashSet<>();
        }
        return set;
    }
    
	@Override
	public Set<String> getCodeChannels() {
		Set<String> set = weixinQRDao.getCodeChannels();
        if (set == null) {
            set = new HashSet<>();
        }
        return set;
	}

    @Override
    public QueryListVO getRedpackList(Map<String, Object> params) {
        Integer count = weixinQRDao.getRedpackCount(params);
        List<WeixinRedpackRecord> data = null;
        if (count != 0) {
            data = weixinQRDao.getRedpackList(params);
        }
        return new QueryListVO(count, data);
    }

    @Override
    public QueryListVO getRedpackStatList(Map<String, Object> params) throws AppException {
        Integer count = weixinQRDao.getRedpackStatCount(params);
        List<WeixinRedpackStat> data = null;
        if (count != 0) {
            data = weixinQRDao.getRedpackStatList(params);
        }
        return new QueryListVO(count, data);
    }

    @Override
    public String exportRedpackList(Map<String, Object> params) {
        Integer count = weixinQRDao.getRedpackCount(params);
        if (count == 0) {
            return "无数据";
        }

        List<WeixinRedpackRecord> data = weixinQRDao.getRedpackList(params);
        StringBuilder sb = new StringBuilder("发放时间,手机号码,金额(单位:元),红包状态,活动名称,服务类型,订单号,领取时间,领取失败原因,交易成功商户订单号,交易失败商户订单号,红包领取状态(同步状态),同步时间\r\n");
        for (WeixinRedpackRecord r : data) {
            String createTimeStr = sdf.format(r.getCreateTime());

            String sendTimeStr;
            if (r.getSendTime() != null) {
                sendTimeStr = sdf.format(r.getSendTime());
            }
            else {
                sendTimeStr = "N/A";
            }

            String status = r.getStatus() == 0 ? "待领取" : (r.getStatus() == 1 ? "已发出" : "已补发");
            String errorMsg;
            if (r.getStatus() == 0) {
                errorMsg = r.getErrorMsg() == null ? "N/A" : r.getErrorMsg();
            }
            else {
                errorMsg = "N/A";
            }

            String successNo = r.getSuccessBillNo();
            String failNo = r.getFailBillNo();
            successNo = successNo == null ? "N/A" : "`" + successNo;
            failNo = failNo == null ? "N/A" : "`" + failNo;

            String state;
            String syncTimeStr;
            if (r.getStatus() != 0) {
                if (StringUtils.isNotBlank(r.getCurrentState())) {
                    switch (r.getCurrentState()) {
                        case "SENDING":
                            state = "发送中";
                            break;
                        case "SENT":
                            state = "已发放, 待领取";
                            break;
                        case "RECEIVED":
                            state = "已经领取";
                            break;
                        case "FAILED":
                            state = "发放失败";
                            break;
                        case "REFUND":
                            state = "已退款";
                            break;
                        default:
                            state = r.getCurrentState();
                    }
                    syncTimeStr = sdf.format(r.getStateTime());
                }
                else {
                    state = "未同步";
                    syncTimeStr = "N/A";
                }
            }
            else {
                state = "N/A";
                syncTimeStr = "N/A";
            }

            sb.append(createTimeStr).append(",");
            sb.append(r.getPhone()).append(",");
            sb.append(r.getMoney() / 100D).append(",");
            sb.append(status).append(",");
            sb.append(r.getActivityName()).append(",");
            sb.append(r.getServiceType()).append(",");
            sb.append("\"").append(r.getBusinessId()).append("\"").append(",");
            sb.append(sendTimeStr).append(",");
            sb.append(errorMsg).append(",");
            sb.append(successNo).append(",");
            sb.append(failNo).append(",");
            sb.append(state).append(",");
            sb.append(syncTimeStr).append("\r\n");
        }

        return sb.toString();
    }

    @Override
    public String exportStatList(Map<String, Object> params) throws AppException {
        Integer count = weixinQRDao.getRedpackStatCount(params);
        if (count == 0) {
            return "无数据";
        }

        List<WeixinRedpackStat> data = weixinQRDao.getRedpackStatList(params);
        StringBuilder sb = new StringBuilder("日期,活动名称,单个红包金额(单位:元),发出红包数,领取红包数,发出总金额(单位:元),领取总金额(单位:元),未领取金额(单位:元),商户平台退款金额(单位:元),商户平台领取金额(单位:元),差异\r\n");
        for (WeixinRedpackStat s : data) {
			sb.append(s.getCdate() != null ? s.getCdate() : "-").append(",");
			sb.append(s.getAct_name() != null ? s.getAct_name() : "-").append(",");
			sb.append(s.getFee() != null ? s.getFee() : "-").append(",");
			sb.append(s.getSend_num() != null ? s.getSend_num() : "-").append(",");
			sb.append(s.getRecv_num() != null ? s.getRecv_num() : "-").append(",");
			sb.append(s.getSend_amount() != null ? s.getSend_amount() : "-").append(",");
			sb.append(s.getRecv_amount() != null ? s.getRecv_amount() : "-").append(",");
			sb.append(s.getNo_recv_amount() != null ? s.getNo_recv_amount() : "-").append(",");
			sb.append(s.getRefund_amount() != null ? s.getRefund_amount() : "-").append(",");
			sb.append(s.getMch_send_amount() != null ? s.getMch_send_amount() : "-").append(",");
            sb.append(s.getDiff_amount() != null ? s.getMch_send_amount() : "-").append("\r\n");
        }

        return sb.toString();
    }

    @Override
    public Set<String> getAllActivityNames() {
        Set<String> result = weixinQRDao.getAllActivityNames();
        return result == null ? new HashSet<String>() : result;
    }

	@Override
	public String exportWeixinList(Map<String, Object> params) {
		Integer count = weixinQRDao.getCount(params);
        if (count == 0) {
            return "无数据";
        }
        
        List<WeixinQRActivityVO> data = weixinQRDao.getList(params);
        StringBuilder sb = new StringBuilder("扫码日期,二维码渠道,优惠码渠道,平台,派券类型,扫码uv,新关注uv,访问链接uv,登记成功uv,领油卡成功uv\r\n");
        for (WeixinQRActivityVO vo : data) {
        	String platform = "";
        	String type = "";
        	switch (vo.getPlatform()) {
				case -2 :
					platform = "未知";
					break;
				case -1 :
					platform = "全平台";
					break;
				case 0 :
					platform = "iOS";
					break;
				case 1 :
					platform = "Android";
					break;
				case 2 :
					platform = "其它";
					break;

				default :
					platform = "未定义";
					break;
			}
        	
        	switch (vo.getType()) {
				case -1 :
					type = "全类型";
					break;
				case 0 :
					type = "实物卡";
					break;
				case 1 :
					type = "不干胶";
					break;

				default :
					type = "未定义";
					break;
			}
        	sb.append(vo.getDate() + ",");
        	sb.append(vo.getCodeChannel() + ",");
        	sb.append(vo.getChannel() + ",");
        	sb.append(platform + ",");
        	sb.append(type + ",");
        	sb.append(vo.getScanUv() + ",");
        	sb.append(vo.getSubscribeUv() + ",");
        	sb.append(vo.getActivityUrlUv() + ",");
        	sb.append(vo.getRegisterUv() + ",");
        	sb.append(vo.getActivateUv() + "\r\n");
        }
        return sb.toString();
	}

}
